package com.example.seataxa.order.service.impl;


import com.example.seataxa.order.feign.AccountFeignClient;
import com.example.seataxa.order.model.Order;
import com.example.seataxa.order.service.OrderService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import static com.alibaba.nacos.client.utils.EnvUtil.LOGGER;

/**
 * @author 季舟
 * @Date 2024-09-14 15:02
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private AccountFeignClient accountFeignClient;

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建订单
     *
     * @param userId        用户ID
     * @param commodityCode 商品编号
     * @param orderCount    订购数量
     */
    @Override
    @Transactional
    public void create(String userId, String commodityCode, int orderCount) {
        LOGGER.info("Order Service Begin ... xid: ");
        // 计算订单金额
        int orderMoney = calculate(commodityCode, orderCount);
        // 从账户余额扣款
        accountFeignClient.debit(userId, orderMoney);

        final Order order = new Order();
        order.userId = userId;
        order.commodityCode = commodityCode;
        order.count = orderCount;
        order.money = orderMoney;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        LOGGER.info(
                "Order Service SQL: insert into order_tbl (user_id, commodity_code, count, money) values ({}, {}, {}, {})",
                userId, commodityCode, orderCount, orderMoney);
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement pst = con.prepareStatement(
                        "insert into order_tbl (user_id, commodity_code, count, money) values (?, ?, ?, ?)",
                        PreparedStatement.RETURN_GENERATED_KEYS);
                pst.setObject(1, order.userId);
                pst.setObject(2, order.commodityCode);
                pst.setObject(3, order.count);
                pst.setObject(4, order.money);
                return pst;
            }
        }, keyHolder);
        order.id = keyHolder.getKey().longValue();
        LOGGER.info("Order Service End ... Created " + order);
    }

    private int calculate(String commodityId, int orderCount) {
        return 200 * orderCount;
    }
}
